import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com', // 替换为您的API基础URL
  timeout: 1000,
  headers: { 'Content-Type': 'application/json' }
});

// 这个变量来标识是否正在刷新Token
let isRefreshing = false;
let refreshSubscribers = [];

function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb);
}

function onRrefreshed(token) {
  refreshSubscribers.map(cb => cb(token));
}

function refreshAccessToken() {
  return axios.post('https://api.example.com/auth/refresh', {
    refreshToken: localStorage.getItem('refreshToken')
  });
}

instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

instance.interceptors.response.use(
  response => response,
  error => {

    // TODO 请求错误的时候，如果token过期，则刷新token
    const { config, response: { status } } = error;
    const originalRequest = config;

    if (status === 401 && !originalRequest._retry) {
      if (!isRefreshing) {
        isRefreshing = true;
        refreshAccessToken().then(response => {
          const newToken = response.data.token;
          localStorage.setItem('token', newToken);
          isRefreshing = false;
          onRrefreshed(newToken);
        }).catch(err => {
          // Handle token refresh error (e.g., log out the user)
          console.error('Token refresh failed:', err);
        });
      }

      const retryOriginalRequest = new Promise(resolve => {
        subscribeTokenRefresh(token => {
          originalRequest.headers.Authorization = `Bearer ${token}`;
          resolve(instance(originalRequest));
        });
      });

      return retryOriginalRequest;
    }

    return Promise.reject(error);
  }
);

export default instance;
